package com.middleware.executor;

import com.middleware.connect.DbConnection;
import com.middleware.parse.ParsedSql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class DatabaseExecutor {

    // 执行查询
    public static ResultSet executeQuery(ParsedSql parsedSql,Connection conn) {
        try  {
            PreparedStatement pstmt = conn.prepareStatement(parsedSql.getFinalSql());
            // 设置参数
            setParameters(pstmt, parsedSql.getParamValues());
            return pstmt.executeQuery();

        } catch (SQLException e) {
            throw new RuntimeException("数据库查询失败", e);
        }
    }

    // 执行更新（insert/update/delete）
    public static int executeUpdate(ParsedSql parsedSql) {
        try (Connection conn = DbConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(parsedSql.getFinalSql())) {

            setParameters(pstmt, parsedSql.getParamValues());
            return pstmt.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException("数据库更新失败", e);
        }
    }

    private static void setParameters(PreparedStatement pstmt, List<Object> parameters) throws SQLException {
        for (int i = 0; i < parameters.size(); i++) {
            pstmt.setObject(i + 1, parameters.get(i));
        }
    }
}